// 资源管理
import React, { Component } from "react";
import { Switch, InputNumber, Tooltip, Modal, message } from "antd";
import { QuestionCircleOutlined } from '@ant-design/icons';
import TheTable from "@/components/TheTable";
import TheTableExtend from "@/components/TheTableExtend";
import ThePagination from "@/components/ThePagination";
import TheButton from "@/components/TheButton";
import TheImage from "@/components/TheImage";
import TheQueryForm from "@/components/TheQueryForm";
import "./style.scss";
import store from "@/store/store"
import _ from 'lodash';
import { thirdResourcePage, thirdResourceUpdateStatus, thirdResourceEdit, thirdResourceDel } from "@/request/tripartiteMall/resourceManagement";
const { confirm } = Modal;

export default class ResourceManagement extends Component {
  constructor(props) {
    super(props)
    this.queryFormRef = React.createRef();
    this.state = {
      columns: [
        {
          title: "资源名称",
          dataIndex: "resourceName",
          key: "resourceName",
        },
        {
          title: "排序",
          dataIndex: "sort",
          key: "sort",
          sortDirections: ['ascend'],
          sorter: true,
          render: (text, record) => {
            return (
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', minWidth:150 }}>
                <InputNumber min={1} max={9999} precision={0} value={text} onChange={this.valueInput} />
                <TheButton style={{ marginLeft: '10px' }} type='primary' onClick={() => { this.sortChange(record.resourceId) }}>确定</TheButton>
              </div>
            )
          }
        },
        {
          title: "所属资源位",
          dataIndex: "resourceType",
          key: "resourceType",
          filterDropdown: true, // 自定义的列筛选功能，我们占位为信息提示Icon的位置
          filterIcon: () => {
            return (
              <Tooltip zIndex={999} placement="top" title={() => {
                return <div>
                  资源只在APP当前资源位中展示<br />
                  多图位：可轮播展示多图<br />
                  单位图：只展示开启中排序第一的单图<br />
                </div>
              }
              }  >
                <QuestionCircleOutlined />
              </Tooltip>
            );
          },
          render: (text) => {
            switch (text) {
              case 1:
                return text = '顶部宣传单图位'
              case 2:
                return text = '首页banner多图位'
              case 3:
                return text = '列表首位多图位'
              case 4:
                return text = '玩法浮标单图位'
              case 5:
                return text = '玩法单图位'
            }
          }
        },
        {
          title: "图片",
          dataIndex: "resourceImage",
          key: "resourceImage",
          render: (text, record) => {
            return <TheImage src={text} width={80} height={80} />
          }
        },
        {
          title: "备注",
          dataIndex: "remark",
          key: "remark",
          render: (text, record) => {
            return <Tooltip title={text}>
              <span className="remark">{text}</span>
            </Tooltip>
          }
        },
        {
          title: "最近保存时间",
          dataIndex: "updateTime",
          key: "updateTime",
        },
        {
          title: "状态",
          dataIndex: "status",
          key: "status",
          render: (text, render) => {
            return <Switch checked={text} onChange={(v) => { this.statusChange(v, render.resourceId) }} />
          },
        },
        {
          title: "操作",
          fixed: 'right',
          render: (text, record) => {
            return (
              <div>
                <TheButton haspermi={['tripartiteMall:resource:edit']} onClick={() => { this.props.history.push(`/tripartiteMall/resourceManagement/edit/${record.resourceId}`) }}>编辑</TheButton>
                <TheButton haspermi={['tripartiteMall:resource:del']} onClick={() => this.delete(record.resourceId)}>删除</TheButton>
              </div>
            );
          }
        },
      ],
      newColumns: [],
      pageData: {
        pageNo: 1,
        pageSize: 10,
      },
      dataSource: [],
      total: 1,
      searchOption: [
        {
          field: "resourceType",
          label: "所属资源位",
          placeholder: "全部",
          type: "Select",
          options: [
            { label: "全部", value: "" },
            { label: "列表首位多图位", value: 3 },
            // { label: "商详页玩法单图位", value: 5 },
          ],
        },
        {
          field: "resourceName",
          label: "资源名称",
          placeholder: "请输入资源名称",
          type: "Input",
        },
        {
          field: "status",
          label: "状态",
          placeholder: "请选择状态",
          type: "Select",
          options: [
            { label: "全部", value: "" },
            { label: "开启", value: 1 },
            { label: "关闭", value: 0 },
          ],
        },
      ],
      form_show: true,
      queryForm: {},
      sort: '',// 排序值
    }
  }
  componentDidMount() {
    this.onColumnsFilter(this.state.columns)
    this.getData()
  }
  // 表格columns变化
  onColumnsFilter(value) {
    this.setState({ newColumns: value })
  }
  // 资源列表
  getData(values) {
    if ( values !== undefined && "resourceName" in values){
      values.resourceName = values.resourceName.trim()
    }
    this.setState({ queryForm: values === undefined ? this.state.queryForm : { ...values} },
      async () => {
        let params = { ...this.state.queryForm, ...this.state.pageData }
        // 页面刷新时搜素缓存
        store.dispatch({
          type: 'SaveSearchValues',
          data: { pathName: 'resourceManagement', ...params }
        })
        let res = await thirdResourcePage({ ...params })
        if (res.code === 0) {
          this.setState({
            dataSource: res.data,
            pageData: { pageNo: res.pageNo, pageSize: res.pageSize },
            total: res.totalCount
          })
        }
      });
  }
  // 开关状态改变
  async statusChange(value, resourceId) {
    let status = value ? 1 : 0
    let text = value ? '开启' : '关闭'
    let res = await thirdResourceUpdateStatus({ resourceId, status })
    if (res.code === 0) {
      message.success(`资源${text}！`)
      this.getData()
    }
  }
  // 排序输入框
  valueInput = (e) => {
    this.setState({ sort: e })
  }
  // 排序修改
  async sortChange(resourceId) {
    let res = await thirdResourceEdit({ editFlag: false, sort: this.state.sort, resourceId })
    if (res.code === 0) {
      message.success('排序修改成功！')
      this.getData()
    }
  }
  // 表格的升序降序
  handleTableChange = (pagination, filters, sorter) => {
    let { queryForm } = this.state
    queryForm.orderByAsc = sorter.order === 'ascend' ? 'sort' : null
    this.setState({ queryForm }, () => { this.getData() })
  }
  // 删除资源配置
  delete(resourceId) {
    React.$confirm({
      title: "提示",
      type: 'warning',
      content: "确定删除该资源吗？",
      onOk: async () => {
        let res = await thirdResourceDel({ resourceId })
        if (res.code === 0) {
          message.success('删除成功！')
          this.delToPageStatus()
        }
      }
    });
  }
  delToPageStatus = ()=>{
    let { pageData,total } = this.state
    if ((total%pageData.pageSize) === 1){
      this.pageChange(pageData.pageNo-1,pageData.pageSize)
    }
    else {
      this.pageChange(pageData.pageNo,pageData.pageSize)
    }
  }
  // 分页切换
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: { pageNo, pageSize }
    }, () => { this.getData() });
  };
  // 重置搜索
  onReset() {
    this.setState({ queryForm: {} }, () => { this.pageChange(1, 10) });
  }
  render() {
    const { columns, dataSource, newColumns, pageData, total, form_show, searchOption, } = this.state
    return (
      <div className='p-layout-box'>
        <TheQueryForm
          ref={(ref) => (this.queryFormRef = ref)}
          show={form_show}
          option={searchOption}
          onGetValues={(values) => this.getData(values)}
          onReset={() => this.onReset()}
        ></TheQueryForm>
        <TheTableExtend
          columns={columns}
          onFormTrigger={() => this.setState({ form_show: !this.state.form_show })}
          onTableRefresh={() => { return dataSource }}
          onColumnsFilter={(value) => this.onColumnsFilter(value)}
        >
          <TheButton haspermi={['tripartiteMall:resource:add']} type="primary" size="middle" onClick={() => { this.props.history.push(`/tripartiteMall/resourceManagement/add`) }}>新增资源</TheButton>
        </TheTableExtend>
        <div className="p-layout-content-pagination">
          <TheTable
            scroll={{ x: "max-content", y: "55vh" }}
            columns={newColumns}
            dataSource={dataSource}
            onChange={this.handleTableChange}
            rowKey={'id'}
          />
          <ThePagination
            pageNo={pageData.pageNo}
            pageSize={pageData.pageSize}
            total={total}
            pageChange={this.pageChange}
          />
        </div>
      </div>
    )
  }
}
